package com.xmcowell.sportpacemaster.utils;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.xmcowell.sportpacemaster.layout.multi.MusicFragment;
import com.xmcowell.sportpacemaster.layout.multi.VideoFragment;

import java.io.File;
import java.util.concurrent.ThreadFactory;

/**
 * Created by Administrator on 2017/8/30 0030.
 */

public class FileUtils {

    /**
     * 根据文件路径，删除文件
     *
     * @param filePath
     */
    public static void delFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile()) {
            Log.e("delFile", "准备删除文件 filePath = " + filePath);
            try {
                file.delete();
                Log.e("delFile", "删除成功");
            } catch (Exception e) {
                Log.e("delFile", "删除失败，error = " + e.toString());
            }
        }
        file.exists();
    }

    /**
     * 从媒体表中删除
     *
     * @param filePath
     */
    public static void delSourceFile(final int flag, final Context context, final String filePath) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String[] retCol = {MediaStore.Audio.Media._ID};
                Cursor cur = context.getContentResolver().query(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        retCol,
                        MediaStore.MediaColumns.DATA + "='" + filePath + "'", null, null);
                if (cur.getCount() != 0) {
                    cur.moveToFirst();
                    int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
                    Log.e("delFile", "id=" + filePath);
                    cur.close();
                    Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
                    context.getContentResolver().delete(uri, null, null);
                }
                delFile(filePath);
                if (flag == 0) {
//                    if (MusicFragment.instance != null && !MusicFragment.instance.isRemoving()) {
//                        MusicFragment.instance.handler.sendEmptyMessage(4);
//                    }
                }
            }
        }).start();
    }

    public static boolean isExits(String path){
        File file = new File(path);
        return file.exists();
    }
}
